﻿using MediatR;
using Microsoft.IdentityModel.Tokens;
using T.Contract.Domain.T.Contract.Model;
using T.Contract.Domain.T.Contract.Model.Dtos;
using T.Contract.Read.API.Application.Command.ContractCommand;
using T.Contract.Repository.Interface;

namespace T.Contract.Read.API.Application.CommandHandlers.ContractHandler
{
    public class ContractHShowCommandHandler : IRequestHandler<ContractHShowCommand, PageDto<ContractModel>>
    {

        protected readonly IContractRepository contractRepository;

        public ContractHShowCommandHandler(IContractRepository contractRepository)
        {
            this.contractRepository = contractRepository;
        }

        public async Task<PageDto<ContractModel>> Handle(ContractHShowCommand request, CancellationToken cancellationToken)
        {
            var res = await contractRepository.GetAsync(o=>o.ContractClassification==1&&o.IsDeleted == false);
            if (!string.IsNullOrEmpty(request.ContractTitle))
            {
                res=res.Where(o=>o.ContractTitle.Contains(request.ContractTitle)).ToList();
            }
            if (!string.IsNullOrEmpty(request.Unit))
            {
                res = res.Where(o => o.Unit.Contains(request.Unit)).ToList();
            }
            if (!string.IsNullOrEmpty(request.PersonCharge))
            {
                res = res.Where(o => o.PersonCharge.Contains(request.PersonCharge)).ToList();
            }
            if (!string.IsNullOrEmpty(request.Attn))
            {
                res = res.Where(o => o.Attn.Contains(request.Attn)).ToList();
            }
            if (request.DateofSigning!=null)
            {
                res = res.Where(o => o.DateofSigning==request.DateofSigning).ToList();
            }
            if (!string.IsNullOrEmpty(request.CompanyID))
            {
                res = res.Where(o => o.CompanyID==request.CompanyID).ToList();
            }
            if (request.CcontractStatus>0)
            {
                res = res.Where(o => o.CcontractStatus == request.CcontractStatus).ToList();
            }
            if (request.Pagesize==null)
            {
                request.Pagesize = res.Count();
            }
            if (request.Pageindex == null)
            {
                request.Pageindex = 1;
            }
            PageDto<ContractModel> page =new PageDto<ContractModel>();
            var size = request.Pagesize;
            var index=request.Pageindex;
            page.TotalCount = res.Count();
            page.PageCount =(int) Math.Ceiling(page.TotalCount*1.0  /(int) size);
            page.list=res.OrderByDescending(o=>o.ContractId).Skip(((int)index - 1) *(int)size).Take((int)size).ToList();
            return page;
            }
    }
}
